package task;

public class TaskRunnerAverage extends AbstractTaskRunner {

	@Override
	public void runTask() {
		
		long totalCost = 0;
		long maxCost = 0;
		long minCost = 0;
		long startTime = 0;
		long cost = 0;
		
		//long totalMax
		int counter = this.getMeasureTime();
		while(counter > 0) {
			//this.getTask().setWorkingsetSize(this.getTask().getWorkingsetSize());
			startTime = System.nanoTime();
			this.getTask().run();
			cost = System.nanoTime() - startTime;
			
			totalCost += cost;
			
			if(minCost == 0) {
				minCost = cost;
			}
			
			if(cost < minCost) {
				minCost = cost;
			}
			
			if(cost > maxCost) {
				maxCost = cost;
			}
			
			counter--;
			
			System.out.print(cost + ", ");
		}
		System.out.println();
		System.out.println(String.format("max = %d, min = %d.", maxCost, minCost));
			
		// if run more than 5 times, get rid of the extremes
		if(this.getMeasureTime() > 5) {
			this.setTaskTimeConsuming((totalCost - maxCost - minCost) / (this.getMeasureTime() - 2));
		}
		else {
			this.setTaskTimeConsuming(totalCost / this.getMeasureTime());
		}
		System.out.println(String.format("average = %d.", this.getTaskTimeConsuming()));
		
		
//		System.out.println("This is TaskRunnerAverage running.");
//		System.out.println("And we are going to run " + this.getRunningTime() + " times.");
		
	}

	@Override
	public String getMeasureStrategy() {
		return "average";
	}

}
